<?php

	// +----------------------------------------------------------------------
	// | 权限组控制器
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\ucenter\admin;

	use app\model\ucenter\AuthGroupAccess;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use app\model\ucenter\AuthGroup as AuthGroupModel;
	use app\model\admin\Menu as MenuModel;
	use app\event\ucenter\AuthGroup as AuthGroupEvent;
	use app\controller\admin\Common;
	use app\model\ucenter\User as UserModel;

	class AuthGroup extends Common
	{
		protected function initialize()
		{
			parent::initialize();
			$this->model = new AuthGroupModel();
		}

		public function _filter()
		{
			return [];
		}

		public function index()
		{
			$map = $this->_filter();
			$map[] = ['type','!=',1];
			// 显示页面
			$builder = new Table();
			$builder->model(AuthGroupModel::class)
				->where($map)
				->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
				->searchText('title', '分组名称：')
				->buttonUpdate('ucenter/admin/AuthGroup/update?type=type')
				->keyId()
				->keyTitle('分组名称')
				->keyText('module', '模块')
				->keyMap('type', '类型', AuthGroupModel::$type_list)
				->keyText('description', '简介')
//				->keyText('level', '操作等级')
				->keyClosure('包含人数', function ($data) {
					if ($data['type'] == 2) {
						return UserModel::where('auth_manage_group_id', $data['id'])->count();
					} elseif (1 == $data['type']) {
						return UserModel::where('auth_admin_group_id', $data['id'])->count();
					} else {
						return UserModel::where('auth_limit_group_id', $data['id'])->count();
					}
				})
//				->keyUpdateTime()
				->keyStatus()
//				->actionUpdate('fast?id={$id}','快速授权')
				->actionManager('update?id={$id}', '管理',function ($data) {
					return 1 == $data['status'] && 1 < $data['id'];
				})
				->actionRestore()
				->actionForbid('forbid?id={$id}', '禁用',function ($data) {
					return 1 == $data['status'] && 1 < $data['id'];
				});
			return $builder->fetch();
		}


		public function background()
		{
			$map = $this->_filter();
			$map[] = ['id','>',1];
			$map[] = ['type','=',1];
			// 显示页面
			$builder = new Table();
			$builder->model(AuthGroupModel::class)
				->where($map)
				->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
				->searchText('title', '分组名称：')
				->buttonUpdate('ucenter/admin/AuthGroup/update?type=type')
				->keyId()
				->keyTitle('分组名称')
				->keyText('module', '模块')
				->keyMap('type', '类型', AuthGroupModel::$type_list)
				->keyText('description', '简介')
//				->keyText('level', '操作等级')
				->keyClosure('包含人数', function ($data) {
					if ($data['type'] == 2) {
						return UserModel::where('auth_manage_group_id', $data['id'])->count();
					} elseif (1 == $data['type']) {
						return UserModel::where('auth_admin_group_id', $data['id'])->count();
					} else {
						return UserModel::where('auth_limit_group_id', $data['id'])->count();
					}
				})
//				->keyUpdateTime()
				->keyStatus()
//				->actionUpdate('fast?id={$id}','快速授权')
				->actionUpdate('update?id={$id}', '管理',function ($data) {
					return 1 == $data['status'] && 1 < $data['id'];
				})
				->actionRestore()
				->actionForbid('forbid?id={$id}', '禁用',function ($data) {
					return 1 == $data['status'] && 1 < $data['id'];
				});
			return $builder->fetch();
		}


		/**
		 * 给用户管理员授权
		 */
		public function group()
		{
			if ($this->request->isPost()) {
//                $result = $this->validate($this->request->post(), 'AuthGroup');
				$user = UserModel::where('id', $this->request->param('user_id'))->find();
				if ($user) {

					AuthGroupAccess::where('user_id', $user['id'])->delete();
					if ($this->request->param('status')) {
						// 授权
						$user['auth_group_id'] = $this->request->param('auth_group_id');
						$user->roles()->save($user['auth_group_id'],['status'=>1]);
					} else {
						$user['auth_group_id'] = null;
					}
					$user->save();
					$this->_returnSuccess('操作成功');
				} else {
					$this->_returnError('用户不存在');
				}

			} else {
				//判断是否为编辑模式
				$user = UserModel::where('id', $this->request->param('user_id'))->find();
				if (!$user) {
					$this->_returnError('会员不存在');
				}
				$data['user_id'] = $user['id'];
				$data['auth_group_id'] = $user['auth_group_id'];
				$data['status'] = empty($data['auth_group_id']) ? 0 : 1;
				$builder = new Edit();
				$builder->title('管理员授权')
					->keyHidden('id')
					->keyHidden('user_id')
					->keySelect('auth_group_id', '管理员组名', AuthGroupModel::where('status', 1)->column('title', 'id'))
//					->keySwitch('status', '启用管理员')
					->data($data)
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		/**
		 * 访问授权页面
		 */
		public function update()
		{
			if ($this->request->isPost()) {
				$event = new AuthGroupEvent();
				$result = $event->rule($this->request->param(), $this->user);
				if (0 === $result['code']) {
					$this->_returnSuccess('修改成功', false);
				} else {
					$this->_returnError('修改失败，失败信息：' . $result['message'], false);
				}
			} else {
				// 同步节点与菜单
				if ($this->request->param('id')) {
					$group_id = $this->request->param('id');
					$auth_group = AuthGroupModel::where('id', $group_id)->find();
					if (!$auth_group) {
						$this->_returnError('权限组不存在');
					}
				} else {
					$auth_group = [];
					$auth_group['rules'] = [];
				}
				if ($auth_group['type'] == 1)
				{
					$this->assign('auth_group', $auth_group);
					$menu_list = $this->AllNodes($auth_group['rules']);
					$this->assign('menu_list', $menu_list);
					$html = $this->fetch();
					$builder = new Edit();
					$builder->form('false')
						->title('基础权限')
						->keyHidden('id')
//						->keySwitch('admin_login', '后台登录', '是否具备登录后台权限')
//						->keySwitch('send_message', '发送消息', '后台管理员直接发送消息')
						->keyCheckBox('message_type', '消息类型', ['站内信', '邮件', '短信'], '允许发的消息类型')
						->keyTextArea('black_ip', '黑名单IP', 'ip地址不可登陆')
						->keyTextArea('white_ip', '白名单IP', 'ip地址可登陆')
						->keyTextInline('title', '用户组名称', '')
						->keyTextArea('description', '描述信息')
//					->keySwitch('status', '启用状态')
						->keyNumber('level', '操作等级', '高等级可以对低等级用户进行操作或者授权')
						->keyHtml('html', $html, '')
						->group('节点访问', 'html')
						->group('分组信息', 'title,description,admin_login,status')
//					->group('高级权限', 'login_error_times,send_message,message_type,level,black_ip,white_ip')
						->data($auth_group)
						->buttonSubmit('', '保存');
					return $builder->fetch();
				}else{

					$builder = new Edit();
					$builder  ->title('基础权限')->keyTextInline('title', '用户组名称', '')
						->keyTextArea('description', '描述信息')
						->keyHidden('id')
						->keyTextArea('black_ip', '黑名单IP', 'ip地址不可登陆')
						->keyTextArea('white_ip', '白名单IP', 'ip地址可登陆')
//						->keyNumber('level', '操作等级', '高等级可以对低等级用户进行操作或者授权')
						->data($auth_group)
						->buttonSubmit();
					return $builder->fetch();
				}

			}
		}


		/**
		 * 返回后台节点数据.
		 */
		protected function AllNodes($rules = [])
		{
			static $nodes = [];
			if ($nodes) {
				return $nodes;
			}
			$list = MenuModel::field('id,title,tip')
				->where('pid', 0)
				->where('hide', 0)
				->where('is_admin', 1)
				->order('sort asc')
				->select();
			foreach ($list as $key1 => $menu) {
				$groups = MenuModel::where('group', '<>', '')->where('pid', $menu['id'])->where('hide', 0)
					->distinct(true)
					->order('sort')
					->column('group');
				$nodes[$key1] = [
					'id' => $menu['id'],
					'title' => $menu['title'],
					'field' => 'nodes[]',
					'spread' => true,
					//                    'checked'=>in_array($menu['id'],$rules)?true:false,
				];
				$temp = [];
				// 查询分组
				if ($groups) {
					foreach ($groups as $key2 => $group) {
						$menus = MenuModel::where('group', $group)->field('id,title,tip')->where('pid', $menu['id'])->where('hide', 0)->order('sort')->select();
						if ($menus) {
							$children = [];
							$checked = false;
							foreach ($menus as $index => $gmenu) {
								$m = $gmenu->toArray();
								$m['field'] = 'nodes[]';
								$actions = MenuModel::where('status', 1)->field('id,title,tip')->where('pid', $m['id'])->where('hide', 0)->order('sort')->select();
								if ($actions->isEmpty()) {
									$m['checked'] = in_array($menu['id'], $rules) ? true : false;
								}
								// 操作节点
								foreach ($actions as $action) {
									$action = $action->toArray();
									$action['checked'] = in_array($action['id'], $rules) ? true : false;
									$action['field'] = 'nodes[]';
									$action['spread'] = true;
									$m['children'][] = $action;
								}

								$children[] = $m;
							}
							$temp[] = [
								'id' => $menu['id'] . '-' . $key2,
								'title' => $group,
								'field' => 'nodes[]',
								'spread' => true,
								'checked' => $checked,
								'children' => $children
							];
						}
					}
				}
				$menus = MenuModel::where('group', '')->field('id,title,tip')->where('pid', $menu['id'])->where('hide', 0)->order('sort')->select();
				if ($menus) {
					foreach ($menus as $index => $menu) {
						$m = $menu->toArray();
						$m['field'] = 'nodes[]';
						$actions = MenuModel::where('status', 1)->field('id,title,tip')->where('pid', $m['id'])->where('hide', 0)->order('sort')->select();
						if ($actions->isEmpty()) {
							$m['checked'] = in_array($menu['id'], $rules) ? true : false;
						}
						// 操作节点
						foreach ($actions as $action) {
							$action = $action->toArray();
							$action['checked'] = in_array($action['id'], $rules) ? true : false;
							$action['field'] = 'nodes[]';
							$action['spread'] = true;
							$m['children'][] = $action;
						}
						$temp[] = $m;
					}
				}
				$nodes[$key1]['children'] = $temp;
			}
			return $nodes;
		}
	}
